package com.geeklan.smart.ui.feed;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.R;
import com.geeklan.smart.common.Constants;
import com.geeklan.smart.data.model.FeedRule;
import com.geeklan.smart.data.repository.pet.PetRepository;
import com.geeklan.smart.databinding.ActivityEditFeedPlanBinding;
import com.geeklan.smart.ui.dialog.ListDialog;
import com.geeklan.smart.ui.dialog.WeekBottomSheetDialog;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModel;
import com.geeklan.smart.ui.viewmodel.pet.PetViewModelFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EditFeedPlanActivity extends BaseActivity<ActivityEditFeedPlanBinding> implements View.OnClickListener {
    private FeedRule feedRule;
    private List<String> hourList;
    private List<String> minList;
    private PetViewModel petViewModel;
    private boolean isEdit = false;
    private FeedRule addFeedRule;
    private String hour = "00", min = "00";
    private String deviceId;
    private ArrayList<FeedRule> feedRules;
    @Override
    protected ActivityEditFeedPlanBinding initBinding() {
        return ActivityEditFeedPlanBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        deviceId = getIntent().getStringExtra("deviceId");
        feedRules = (ArrayList<FeedRule>) getIntent().getSerializableExtra("feedRules");
        petViewModel = new ViewModelProvider(this, new PetViewModelFactory(new PetRepository())).get(PetViewModel.class);
        petViewModel.getUpdateFeedPlanLiveData().observe(this, response -> {
            dismiss();
            Toast.makeText(this, R.string.update_success, Toast.LENGTH_SHORT).show();
            setResult(RESULT_OK);
            finish();
        });

        petViewModel.getUpdateFeedPlanErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });

        feedRule = (FeedRule) getIntent().getSerializableExtra("feedRule");
        if (feedRule != null) {
            isEdit = true;
            mBinding.rgTitle.setText(R.string.update_plan);
        } else {
            addFeedRule = new FeedRule();
            addFeedRule.setDeviceId(deviceId);
            addFeedRule.setRepetitionPeriod("0");
            addFeedRule.setStartTime("00:00");
            addFeedRule.setFeedType(0);
            addFeedRule.setFeedNum(1);
            addFeedRule.setFeedRule("2");
            addFeedRule.setEffectivTime("1");
            addFeedRule.setIsOpen(1);
        }
        initDateWheelView();
    }

    private void initDateWheelView() {
        hourList = new ArrayList<>();
        minList = new ArrayList<>();

        for (int hour = 0; hour <= 23; hour++) {
            hourList.add(String.valueOf(hour < 10 ? ("0" + hour) : hour));
        }
        for (int min = 0; min <= 59; min++) {
            minList.add(String.valueOf(min < 10 ? ("0" + min) : min));
        }

        if (feedRule == null) {
            addFeedRule.setStartTime(hour + ":" + min);
        }
    }

    @Override
    protected void initView() {
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.llRepetitionPeriod.setOnClickListener(this);
        mBinding.llFeedCategory.setOnClickListener(this);
        mBinding.llNumber.setOnClickListener(this);
        mBinding.llFeedMethod.setOnClickListener(this);

        mBinding.llCheckNextDay.setOnClickListener(this);
        mBinding.llCheckNow.setOnClickListener(this);
        mBinding.cbCheckNextDay.setOnClickListener(this);
        mBinding.cbCheckNow.setOnClickListener(this);
        mBinding.tvSave.setOnClickListener(this);


        mBinding.wvHour.setUnit(getString(R.string.hour));
        mBinding.wvHour.setCyclic(true); // 禁止循环滚动
        mBinding.wvHour.setAdapter(new ArrayWheelAdapter<>(hourList));
        mBinding.wvHour.setOnItemSelectedListener(index -> {
            hour = hourList.get(index);
            if (feedRule != null) {
                feedRule.setStartTime(hour + ":" + min);
            } else {
                addFeedRule.setStartTime(hour + ":" + min);
            }
        });

        mBinding.wvMin.setUnit(getString(R.string.min));
        mBinding.wvMin.setCyclic(true);
        mBinding.wvMin.setAdapter(new ArrayWheelAdapter<>(minList));
        mBinding.wvMin.setOnItemSelectedListener(index -> {
            min = minList.get(index);
            if (feedRule != null) {
                feedRule.setStartTime(hour + ":" + min);
            } else {
                addFeedRule.setStartTime(hour + ":" + min);
            }
        });

        int hours = 0,minutes = 0;

        if(feedRule != null){
            String startTime = feedRule.getStartTime();
            if(!TextUtils.isEmpty(startTime)) {
                String[] parts = startTime.split(":");
                hours = Integer.parseInt(parts[0]);
                minutes = Integer.parseInt(parts[1]);
            }
        }

        mBinding.wvHour.setCurrentItem(hours);
        mBinding.wvMin.setCurrentItem(minutes);

        initUI();
    }

    private void initUI() {
        FeedRule fr;
        if (feedRule != null) {
            fr = feedRule;
        } else {
            fr = addFeedRule;
        }

        if (fr.getRepetitionPeriod().contains("0")) {
            mBinding.tvWeeks.setText(getString(R.string.every_day));
        } else {
            StringBuilder stringBuilder = new StringBuilder("");
            String[] weeksStr = fr.getRepetitionPeriod().split(",");
            for (String string : weeksStr) {
                int week = Integer.parseInt(string);
                if (week - 1 >= 0) {
                    stringBuilder.append(Constants.WEEKDAYS[week - 1]).append(" ");
                }
            }
            mBinding.tvWeeks.setText(stringBuilder);
        }

        List<String> feedType = Arrays.asList(getResources().getStringArray(R.array.feed_type));
        mBinding.tvType.setText(feedType.get(fr.getFeedType()));

        if (fr.getFeedType() == 0) {
            mBinding.tvNumber.setText(setItems1().get(fr.getFeedNum() - 1));
        } else {
            mBinding.tvNumber.setText(setItems2().get(fr.getFeedNum() - 1));
        }

        List<String> list = Arrays.asList(getResources().getStringArray(R.array.feed_rule));
        if ("1".equals(fr.getFeedRule())) {
            mBinding.tvMethod.setText(list.get(0));
        } else {
            mBinding.tvMethod.setText(list.get(1));
        }

        if ("1".equals(fr.getEffectivTime())) {
            mBinding.cbCheckNow.setChecked(true);
            mBinding.cbCheckNextDay.setChecked(false);
        } else {
            mBinding.cbCheckNow.setChecked(false);
            mBinding.cbCheckNextDay.setChecked(true);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == mBinding.llRepetitionPeriod.getId()) {
            WeekBottomSheetDialog weekBottomSheetDialog = getWeekBottomSheetDialog();
            weekBottomSheetDialog.show();
        } else if (id == mBinding.llFeedCategory.getId()) {
            ListDialog listDialog = getFeedTypeDialog();
            listDialog.show();
        } else if (id == mBinding.llNumber.getId()) {
            ListDialog listDialog = null;
            if (feedRule != null) {
                listDialog = getNumberDialog(feedRule.getFeedType());
            } else {
                listDialog = getNumberDialog(addFeedRule.getFeedType());
            }
            listDialog.show();
        } else if (id == mBinding.llFeedMethod.getId()) {
            ListDialog listDialog = getFeedMethodDialog();
            listDialog.show();
        } else if (id == mBinding.llCheckNextDay.getId()) {
            mBinding.cbCheckNow.setChecked(false);
            mBinding.cbCheckNextDay.setChecked(true);
            if (feedRule != null) {
                feedRule.setEffectivTime("2");
            } else {
                addFeedRule.setEffectivTime("2");
            }
        } else if (id == mBinding.llCheckNow.getId()) {
            mBinding.cbCheckNow.setChecked(true);
            mBinding.cbCheckNextDay.setChecked(false);
            if (feedRule != null) {
                feedRule.setEffectivTime("1");
            } else {
                addFeedRule.setEffectivTime("1");
            }
        } else if (id == mBinding.cbCheckNextDay.getId()) {
            mBinding.cbCheckNow.setChecked(false);
            if (feedRule != null) {
                feedRule.setEffectivTime("2");
            } else {
                addFeedRule.setEffectivTime("2");
            }
        } else if (id == mBinding.cbCheckNow.getId()) {
            mBinding.cbCheckNextDay.setChecked(false);
            if (feedRule != null) {
                feedRule.setEffectivTime("1");
            } else {
                addFeedRule.setEffectivTime("1");
            }
        } else if (id == mBinding.tvSave.getId()) {

            if (isEdit) {
                petViewModel.updateFeedRule(feedRule);
            } else {
                for (FeedRule rule : feedRules) {
                    if(rule.getStartTime().equals(addFeedRule.getStartTime()) || hasCommonDigit(rule.getRepetitionPeriod(),addFeedRule.getRepetitionPeriod())){
                        Toast.makeText(this,"请勿设置同时间的规则",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                petViewModel.addFeedRule(addFeedRule);
            }
            loading();
        }
    }

    public static boolean hasCommonDigit(String str1, String str2) {
        if ("0".equals(str1) || "0".equals(str2)) {
            return false;
        }

        for (char c1 : str1.toCharArray()) {
            if (str2.indexOf(c1) != -1) {
                return true;
            }
        }

        return false;
    }

    private List<String> setItems1() {
        List<String> items = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            items.add(i + " 条");
        }
        return items;
    }

    private List<String> setItems2() {
        List<String> items = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            items.add(i + " 份（约" + i * 20 + "g）");
        }
        return items;
    }

    private ListDialog getFeedTypeDialog() {
        ListDialog listDialog = new ListDialog(this);
        List<String> feedType = Arrays.asList(getResources().getStringArray(R.array.feed_type));
        listDialog.setupWheelViews(feedType);
        listDialog.setDialogTitle(getString(R.string.settings_feed_type));
        listDialog.setOnBackListener(position -> {
            if (feedRule != null) {
                feedRule.setFeedType(position);
            } else {
                addFeedRule.setFeedType(position);
            }

            if (position == 0) {
                mBinding.tvNumber.setText(setItems1().get(0));
            } else {
                mBinding.tvNumber.setText(setItems2().get(0));
            }

            mBinding.tvType.setText(feedType.get(position));
        });
        return listDialog;
    }

    private ListDialog getFeedMethodDialog() {
        ListDialog listDialog = new ListDialog(this);
        List<String> list = Arrays.asList(getResources().getStringArray(R.array.feed_rule));
        listDialog.setupWheelViews(list);
        listDialog.setDialogTitle(getString(R.string.settings_feed_method));
        listDialog.setOnBackListener(position -> {
            if (feedRule != null) {
                feedRule.setFeedRule(String.valueOf(position + 1));
            } else {
                addFeedRule.setFeedRule(String.valueOf(position + 1));
            }
            mBinding.tvMethod.setText(list.get(position));
        });
        return listDialog;
    }

    private ListDialog getNumberDialog(int type) {
        ListDialog listDialog = new ListDialog(this);
        if (type == 0) {
            listDialog.setupWheelViews(setItems1());
        } else {
            listDialog.setupWheelViews(setItems2());
        }
        listDialog.setDialogTitle(getString(R.string.settings_feed_number));
        listDialog.setOnBackListener(position -> {
            if (feedRule != null) {
                feedRule.setFeedNum(position + 1);
            } else {
                addFeedRule.setFeedNum(position + 1);
            }

            if (type == 0) {
                mBinding.tvNumber.setText(setItems1().get(position));
            } else {
                mBinding.tvNumber.setText(setItems2().get(position));
            }
        });
        return listDialog;
    }

    private WeekBottomSheetDialog getWeekBottomSheetDialog() {
        WeekBottomSheetDialog weekBottomSheetDialog = new WeekBottomSheetDialog(this);
        weekBottomSheetDialog.setSelectWeekListener(weeks -> {
            String repetitionPeriod = "";
            if (weeks.contains("0")) {
                repetitionPeriod = "0";
                mBinding.tvWeeks.setText(getString(R.string.every_day));
            } else {
                StringBuilder stringBuilder = new StringBuilder("");
                String[] weeksStr = weeks.split(",");
                for (String string : weeksStr) {
                    int week = Integer.parseInt(string);
                    if (week - 1 >= 0) {
                        stringBuilder.append(Constants.WEEKDAYS[week - 1]).append(" ");
                    }
                }
                repetitionPeriod = weeks;
                mBinding.tvWeeks.setText(stringBuilder);
            }
            if (feedRule != null) {
                feedRule.setRepetitionPeriod(repetitionPeriod);
            } else {
                addFeedRule.setRepetitionPeriod(repetitionPeriod);
            }
        });
        weekBottomSheetDialog.setCancelableOutside(true); // 点击背景关闭
        return weekBottomSheetDialog;
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            getWindow().setStatusBarColor(Color.WHITE);
            return insets;
        });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static Intent startActivity(Context context, FeedRule responseFeedRule,String deviceId,ArrayList<FeedRule> feedRules) {
        Intent intent = new Intent(context, EditFeedPlanActivity.class);
        intent.putExtra("feedRule", responseFeedRule);
        intent.putExtra("feedRules", feedRules);
        intent.putExtra("deviceId",deviceId);
        return intent;
    }

    public static void startActivity(Context context,String deviceId,ArrayList<FeedRule> feedRules) {
        Intent intent = new Intent(context, EditFeedPlanActivity.class);
        intent.putExtra("deviceId",deviceId);
        intent.putExtra("feedRules", feedRules);
        context.startActivity(intent);
    }
}